<?php
class Admin_StudentController extends Zend_Controller_Action {
	
     public function init(){
		Zend_Loader::loadClass('AdminModel');
		Zend_Loader::loadClass('TeacherModel');
		Zend_Loader::loadClass('LoginModel');
		Zend_Loader::loadClass('StudentsModel');
	}
	
    function preDispatch(){
    	/*
    	 * Kiem tra dang nhap
    	 */
		
		$auth = Zend_Auth::getInstance();
		if(strcmp($this->_request->getActionName(),'login')!=0){
			if (!$auth->hasIdentity()) {
				$this->_redirect('/admin/index/login');
			}
		}
		/*
		 * Tra cac thong tin ve moduln cho view
		*/
		$this->view->module = $this->_request->getModuleName();
		$this->view->controller =  $this->_request->getControllerName();
		$this->view->action =  $this->_request->getActionName();
		/*
		 * Load template
		*/
		$layoutPath = APPLICATION_PATH  . '/templates/admin/admin';
		$option = array (	'layout' 		=> 'index',
				'layoutPath' 	=> $layoutPath );
		Zend_Layout::startMvc ( $option );
	}
	
	function indexAction(){
		/*
		 * Lay danh sach sinh vien (co phan trang)
		 */
		if($this->_request->isPost()){
		$name_search = $this->_request->getParam('name_search');
		$shsv_search = $this->_request->getParam('shsv_search');
		
        //echo $code_search.'|'.$c_search;die;
        
        $this->view->shsv_search = $shsv_search;
		$this->view->name_search = $name_search;
		
        $list = StudentsModel::search($shsv_search,$name_search);
		//Zend_Debug::dump($list);die;
        
        $this->view->list = $list;
		$this->view->search = 1;
    	}
        
        else{
        $page = $this->_request->getParam('page');
		if(!$page) $offset = 1;
		else $offset = $page;
		$this->view->now_page = $offset;
		$this->view->count = count(StudentsModel::getAllStudent());
		$list = StudentsModel::selectLimitStudent(30,($offset-1)*30);
		$this->view->list = $list;
 	    $this->view->search = 0;
    	
        }
	}
    
    public function addAction(){
           if($this->_request->isPost()){
            
            $name= $this->_request->getParam('name');
            $birthday= $this->_request->getParam('birthday');
            $shsv= $this->_request->getParam('shsv');
            $class= $this->_request->getParam('class');
            $username= $this->_request->getParam('username');
            $password= $this->_request->getParam('password');
            $course= $this->_request->getParam('course');
            $status= $this->_request->getParam('status');
            
          
            $data= array('name'=>$name,
                         'birthday'=>$birthday,
                         'shsv'=>$shsv,
                         'class'=>$class,
                         'username'=>$username,
                         'password'=>base64_encode($password),
                         'course'=>$course,
                         'status'=>$status
                         
            );
            
    
            
            if($name!='' && $shsv!='' && $class!='' && $username!='' && $password!='' && $course!=''){
                $model= new StudentsModel();
                $model->insert($data);
                $this->_redirect('/admin/student');          
                
            }else{
                $this->view->warning = 1;
                $this->view->data= $data;
            }
        
        }
    }
    
    public function editAction(){
        if($_REQUEST['id']!=''){
            $id= $_REQUEST['id'];
            $model= new StudentsModel();
            $this->view->data= $model->getDbbyID($id);
        }
        if(($_REQUEST['do']=='edit')&&($_REQUEST['id']!='')&&$this->_request->isPost()){
            $id= $_REQUEST['id'];
            $name= $this->_request->getParam('name');
            $birthday= $this->_request->getParam('birthday');
            $shsv= $this->_request->getParam('shsv');
            $class= $this->_request->getParam('class');
            $username= $this->_request->getParam('username');
            $password= $this->_request->getParam('password');
            $course= $this->_request->getParam('course');
            $status= $this->_request->getParam('status');
            
          
            $data= array('name'=>$name,
                         'birthday'=>$birthday,
                         'shsv'=>$shsv,
                         'class'=>$class,
                         'username'=>$username,
                         'password'=>base64_encode($password),
                         'course'=>$course,
                         'status'=>$status
                         
            );
            
    
           // Zend_Debug::dump($data);die;
            if($name!='' && $shsv!='' && $class!='' && $username!='' && $password!='' && $course!=''){
                $model->update($data,"id=".$id);
                $this->_redirect('/admin/student');          
                
            }else{
                $this->view->warning = 1;
            }
        
        }
    }
    
    public function delAction(){
   	    $dt = new StudentsModel;
    	$request = $this->getRequest();
    	$id = $request->getParam('id');
    	if($id){
    		$dt->delete("id=".$id);
    	}
    	exit();
    }
	
	function importExcelStudentAction(){
		
		require_once 'file/excel/excel_reader.php';
		
		if($this->_request->isPost()){
	
			/*
			 * Thiết lập kích thước tối đa (10 MB) cho file sẽ upload lên.
			* Chỉ cho phép upload file định dạng xls
			*/
			$maxSize = 1048576;
			$temp = preg_split('/[\/\\\\]+/', $_FILES["file"]["name"]);
			$filename = $temp[count($temp)-1];
			 
			// Kiểm tra phần mở rộng của file xem có đúng định dạng hay không.
			if (preg_match('/\.(xls|xlsx)$/i', $filename )) {
				if($_FILES["file"]["size"] < $maxSize){
					$dt = new TeacherModel();
					$name_file = $dt->uploadFile();
					//	echo $name_file;die;
					/*
					 * Lấy file excel cần xử lý và require thư viện xử lý file excel.
					* Nhung thu vien xu ly ma nguon mo
					*/
					$filename= "file/excel/".$name_file;
	
	
					/*
					 * Khoi tao doi tuong doc file excel
					*/
					$data = new Spreadsheet_Excel_Reader($filename,true,"UTF-8");
					$rowsnum = $data->rowcount($sheet_index=0); // lay so hang cua sheet
					$colsnum =  $data->colcount($sheet_index=0); // lay so cot cua sheet
	
					/*
					 * Đọc dữ liệu và ghi vào database.
					*/

					$arr_student_add = array();
					$arr_student_edit = array();
					$arr_student_error = array();

					for ($i=2;$i<=$rowsnum;$i++){
						$max = 0;
						/*
						 * Lay thong tin sv tu file excel
						 */
						$sv["name"] = trim($data->val($i,2));
						$sv["birthday"] = $data->val($i,3);
						$sv["shsv"] = $data->val($i,4);
						$sv["class"] = $data->val($i,5);
						$sv["course"] = $data->val($i,6);
						if($sv["name"] && $sv["shsv"]){
							/*
							 *  Tao username cho sv
							 */
					/*		$arr_hoten = explode(" ", $sv["name"]);
							$max = count($arr_hoten);
							
							$ten = $arr_hoten[$max-1];
							$sv["username"] = strtolower(StudentsModel::vi2en($ten));
							
							for ($j = 0; $j < $max -1; $j++){
								if($arr_hoten[$j]){
									$sub_str = StudentsModel::vi2en($arr_hoten[$j]);
									$sv["username"] .= strtolower(substr($sub_str, 0,1));
								}
							}  */
							$sv["username"] = $sv["shsv"];
							/*
							 * Tao pass ngau nhien
							 */
							$sv["password"] = base64_encode(StudentsModel::randString(8));
							$sv["status"] = 0;
							/*
							 * Them sv vao database
							 */
							$check_id_sv_exits = StudentsModel::getIdStudentByShsv($sv["shsv"]);
							if(!$check_id_sv_exits){
								StudentsModel::add($sv);
								$arr_student_add[] = $sv;
							}
							else{
								$sv["id"] = $check_id_sv_exits;
								StudentsModel::edit($sv);
								$arr_student_edit[] = $sv;
							}
						}
						else{
							$arr_student_error[] = $sv;
						}
					}
					$this->view->success = 1;
				}
				else{
	
					$this->view->warning = 1;
				}
				$this->view->s_add = $arr_student_add;
				$this->view->s_edit = $arr_student_edit;
				$this->view->s_error = $arr_student_error;
			}
			else{
				 
				$this->view->warning = 2;
			}
		}
		
	}
	
}